<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多人游戏 (Protobuf版本)</title>
    <script src="protobuf.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 600px;
            text-align: center;
        }
        h2 {
            margin-bottom: 20px;
        }
        .input-section {
            margin-bottom: 20px;
            text-align: left;
        }
        .input-group {
            margin-bottom: 15px;
        }
        .input-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .input-group input, .input-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .start-game-button {
            width: 100%;
            padding: 15px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 18px;
            font-weight: bold;
            margin-top: 20px;
        }
        .start-game-button:hover {
            background-color: #1e7e34;
        }
        .start-game-button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .current-room {
            margin-top: 20px;
            padding: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
        }
        .grid {
            display: grid;
            grid-template-columns: repeat(50, 10px);
            grid-template-rows: repeat(50, 10px);
            margin-top: 20px;
            width: 500px;
            height: 500px;
            overflow: hidden;
        }
        .grid .cell {
            width: 10px;
            height: 10px;
            border: 1px solid #ddd;
            position: relative;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        .grid .cell:hover {
            background-color: #f0f0f0;
        }
        .grid:focus {
            outline: 2px solid #007bff;
            outline-offset: 2px;
        }
        .grid .player {
            width: 40px;
            height: 40px;
            border-radius: 0;
            position: absolute;
            top: 5px;
            left: 5px;
            border: 2px solid #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
            cursor: pointer;
            transition: transform 0.2s ease;
            z-index: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }
        .grid .player:hover {
            transform: scale(1.1);
        }
        .player-list {
            margin-top: 20px;
            list-style: none;
            padding: 0;
        }
        .player-list li {
            padding: 5px 0;
        }
        .hidden {
            display: none;
        }
        .loading {
            color: #666;
            font-style: italic;
        }
        .emoji-grid {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 8px;
        }
        .emoji-item {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            font-size: 24px;
            background-color: white;
            border: 2px solid #ddd;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            user-select: none;
        }
        .emoji-item:hover {
            border-color: #007bff;
            transform: scale(1.1);
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
        }
        .emoji-animation {
            position: absolute;
            font-size: 24px;
            pointer-events: none;
            z-index: 1000;
            animation: emojiFloat 3s ease-out forwards;
            top: -30px;
            left: 50%;
            transform: translateX(-50%);
        }
        @keyframes emojiFloat {
            0% {
                opacity: 0;
                transform: translateX(-50%) scale(0.5) translateY(0);
            }
            20% {
                opacity: 1;
                transform: translateX(-50%) scale(1.2) translateY(-20px);
            }
            80% {
                opacity: 1;
                transform: translateX(-50%) scale(1) translateY(-40px);
            }
            100% {
                opacity: 0;
                transform: translateX(-50%) scale(0.8) translateY(-60px);
            }
        }
        @keyframes playerHighlight {
            0% {
                transform: scale(1);
                box-shadow: 0 0 15px rgba(0, 255, 255, 0.8), 0 0 25px rgba(255, 0, 255, 0.6);
            }
            25% {
                transform: scale(1.2);
                box-shadow: 0 0 25px rgba(0, 255, 255, 1), 0 0 35px rgba(255, 0, 255, 0.8), 0 0 45px rgba(255, 255, 0, 0.6);
            }
            50% {
                transform: scale(1.4);
                box-shadow: 0 0 35px rgba(0, 255, 255, 1), 0 0 45px rgba(255, 0, 255, 1), 0 0 55px rgba(255, 255, 0, 0.8), 0 0 65px rgba(255, 0, 0, 0.6);
            }
            75% {
                transform: scale(1.2);
                box-shadow: 0 0 25px rgba(0, 255, 255, 1), 0 0 35px rgba(255, 0, 255, 0.8), 0 0 45px rgba(255, 255, 0, 0.6);
            }
            100% {
                transform: scale(1);
                box-shadow: 0 0 15px rgba(0, 255, 255, 0.8), 0 0 25px rgba(255, 0, 255, 0.6);
            }
        }
        .player-highlight {
            animation: playerHighlight 1s ease-in-out 3;
        }
    </style>
</head>
<body>

<div class="container">
            <h2>欢迎来到多人游戏</h2>

    <div class="input-section" id="inputSection">
        <div class="input-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" placeholder="请输入用户名" maxlength="20">
        </div>

        <button class="start-game-button" onclick="startGame()">开始游戏</button>
    </div>

    <div class="current-room hidden" id="currentRoom">
        <button onclick="showInputSection()" style="float: right; padding: 5px 10px; background-color: #dc3545; color: white; border: none; border-radius: 3px; cursor: pointer;">返回</button>
    </div>

    <div class="control-info hidden" id="controlInfo" style="margin-top: 10px; padding: 10px; background-color: #f8f9fa; border-radius: 5px; font-size: 14px; color: #666;">
        <strong>控制说明：</strong><br>
        鼠标点击网格或使用键盘控制移动<br>
        <span style="font-family: monospace;">↑↓←→</span> 或 <span style="font-family: monospace;">WASD</span> 键移动<br>
        <span style="font-family: monospace;">R</span> 键重置位置到中心<br>
        <strong>房间限制：</strong> 每个房间最多1000人<br>
        <button onclick="resetPlayerPosition()" style="margin-top: 10px; padding: 5px 10px; background-color: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer;">重置位置</button>
    </div>

    <div class="emoji-panel hidden" id="emojiPanel" style="margin-top: 15px; padding: 15px; background-color: #f8f9fa; border-radius: 5px;">
        <div style="margin-bottom: 10px; font-weight: bold; color: #333;">发送表情包</div>
        <div class="emoji-grid">
            <div class="emoji-item" onclick="sendEmoji('😀')" title="开心">😀</div>
            <div class="emoji-item" onclick="sendEmoji('😂')" title="笑哭">😂</div>
            <div class="emoji-item" onclick="sendEmoji('😍')" title="爱心">😍</div>
            <div class="emoji-item" onclick="sendEmoji('🤔')" title="思考">🤔</div>
            <div class="emoji-item" onclick="sendEmoji('👍')" title="点赞">👍</div>
            <div class="emoji-item" onclick="sendEmoji('👎')" title="踩">👎</div>
            <div class="emoji-item" onclick="sendEmoji('🎉')" title="庆祝">🎉</div>
            <div class="emoji-item" onclick="sendEmoji('💪')" title="加油">💪</div>
            <div class="emoji-item" onclick="sendEmoji('🔥')" title="火">🔥</div>
            <div class="emoji-item" onclick="sendEmoji('⭐')" title="星星">⭐</div>
            <div class="emoji-item" onclick="sendEmoji('❤️')" title="爱心">❤️</div>
            <div class="emoji-item" onclick="sendEmoji('😭')" title="大哭">😭</div>
        </div>
    </div>

    <div class="grid hidden" id="gameGrid"></div>

    <ul class="player-list hidden" id="playerList"></ul>
</div>

<script>
    var socket = null;
    var currentRoom = null;
    var currentPlayer = null;
    var playerElements = {};

    document.getElementById('username').value = new Date()*1;

    async function startGame() {
        const username = document.getElementById('username').value.trim();

        if (!username) {
            alert('请输入用户名');
            return;
        }

        const startButton = document.querySelector('.start-game-button');
        startButton.textContent = '正在加入游戏...';
        startButton.disabled = true;

        try {
            const response = await fetch('/api/game/join', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + 'eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi55So5oi3XzE3NTUxNjc3NjMyMjEiLCJpZCI6NjYsInN1YiI6IjI2MDE4MDM3NTRAcXEuY29tIiwiaWF0IjoxNzU1MTY3NzYzLCJleHAiOjE3NjM4MDc3NjN9.n_L6e7FY8My0rZHlFLrh72fn05uoao3uJYj1Ms0kZH0'
                },
                body: JSON.stringify({
                    username: username,
                    status: 'online',
                    position: { x: 0, y: 0 }
                })
            });

            const result = await response.json();

            if (result.data.success) {
                currentPlayer = {
                    id: username,
                    username: username,
                    status: 'online',
                    position: { x: 0, y: 0 },
                    roomId: result.data.roomId
                };
                currentRoom = result.data.roomId;
                // 拿到房间号后开始连接WebSocket
                connectWebSocket();
                enterGame(result.data.roomId);
            } else {
                alert('加入失败: ' + result.data.message);
                startButton.textContent = '开始游戏';
                startButton.disabled = false;
            }
        } catch (error) {
            console.error('加入游戏失败:', error);
            alert('加入游戏失败，请重试');
            startButton.textContent = '开始游戏';
            startButton.disabled = false;
        }
    }

    function connectWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.hostname}:8082/ws-protobuf`;
        console.log('Protobuf WebSocket URL:', wsUrl)
        socket = new WebSocket(wsUrl);

        // 监听连接建立的事件
        socket.onopen = function(event) {
            console.log('WebSocket连接已建立');
            sendJoinGame();
        };
        // setInterval(()=>{
        //     socket.send(JSON.stringify({ type: 'PING'}))
        // },1000)
        // 监听接收消息的事件
        socket.onmessage = function(event) {
            try {
                const message = ProtobufMessage.fromJSON(event.data);
                if (message) {
                    console.log('收到protobuf消息:', message);
                    handleProtobufMessage(message);
                } else {
                    console.error('解析protobuf消息失败');
                }
            } catch (error) {
                console.error('解析WebSocket消息失败:', error);
            }
        };

        // 监听连接关闭的事件
        socket.onclose = function(event) {
            console.log('WebSocket连接已关闭');
        };

        // 监听连接错误事件
        socket.onerror = function(error) {
            console.error('WebSocket错误:', error);
        };
    }

    function sendJoinGame() {
        if (socket && socket.readyState === WebSocket.OPEN) {
            const message = new ProtobufMessage();
            message.setBase(MessageType.JOIN_GAME, currentPlayer.id, currentRoom);
            message.setJoinGame(currentPlayer);
            
            console.log('发送protobuf加入游戏消息:', message.toJSON());
            socket.send(message.toJSON());
        }
    }

    function handleProtobufMessage(message) {
        const payload = message.getPayload();
        if (!payload) return;
        
        switch (payload.type) {
            case 'room_update':  // 房间更新
                updatePlayerList(payload.players || []);
                break;
            case 'player_move':  // 玩家移动
                if (payload.player) {
                    updatePlayerPosition(payload.player);
                }
                break;
            case 'emoji_sent':   // 有人发送表情包
                if (message.getFrom() !== currentPlayer.id) {
                    showEmojiAnimation(payload.emoji, payload.username, message.getFrom());
                }
                break;
            case 'error':
                alert('错误: ' + payload.message);
                break;
            case 'heartbeat':
                console.log('收到心跳响应');
                break;
            default:
                console.log('收到未知消息类型:', payload.type);
        }
    }

    function enterGame(roomId) {
        document.getElementById("currentRoom").innerHTML =
            `<span>当前房间: ${roomId}</span><button onclick="showInputSection()" style="float: right; padding: 5px 10px; background-color: #dc3545; color: white; border: none; border-radius: 3px; cursor: pointer;">返回</button>`;

        document.getElementById('inputSection').classList.add('hidden');
        document.getElementById('currentRoom').classList.remove('hidden');
        document.getElementById('gameGrid').classList.remove('hidden');
        document.getElementById('playerList').classList.remove('hidden');
        document.getElementById('controlInfo').classList.remove('hidden');
        document.getElementById('emojiPanel').classList.remove('hidden');

        document.getElementById("playerList").innerHTML = '';
        document.querySelectorAll('.player').forEach(function(playerElement) {
            playerElement.remove();
        });
        renderGrid();

        fetch('/api/game/room/' + roomId)
            .then(r => r.json())
            .then(res => {
                if (res && (res.code === '200' || res.code === 200)) {
                    const players = res.data && res.data.players ? res.data.players : [];
                    updatePlayerList(players);
                    try {
                        const me = players.find(p => String(p.id) === String(currentPlayer.id));
                        if (me && me.position) {
                            currentPlayer.position = { x: me.position.x, y: me.position.y };
                        }
                    } catch (e) {}
                }
            })
            .catch(() => {});
    }

    function showInputSection() {
        if (currentPlayer && currentRoom) {
            sendLeaveGame();
        }

        if (socket) {
            socket.close();
            socket = null;
        }

        document.getElementById('inputSection').classList.remove('hidden');
        document.getElementById('currentRoom').classList.add('hidden');
        document.getElementById('gameGrid').classList.add('hidden');
        document.getElementById('playerList').classList.add('hidden');
        document.getElementById('controlInfo').classList.add('hidden');
        document.getElementById('emojiPanel').classList.add('hidden');

        const startButton = document.querySelector('.start-game-button');
        startButton.textContent = '开始游戏';
        startButton.disabled = false;

        document.getElementById('username').value = '';

        currentRoom = null;
        currentPlayer = null;
        playerElements = {};
    }

    function sendLeaveGame() {
        if (socket && socket.readyState === WebSocket.OPEN) {
            const message = new ProtobufMessage();
            message.setBase(MessageType.LEAVE_GAME, currentPlayer.id, currentRoom);
            message.setLeaveGame(currentPlayer);
            
            console.log('发送protobuf离开游戏消息:', message.toJSON());
            socket.send(message.toJSON());
        }
    }

    function renderGrid() {
        const gameGrid = document.getElementById("gameGrid");
        gameGrid.innerHTML = '';
        for (let row = 0; row < 50; row++) {
            for (let col = 0; col < 50; col++) {
                const cell = document.createElement("div");
                cell.classList.add("cell");
                cell.setAttribute("data-x", col);
                cell.setAttribute("data-y", row);
                cell.addEventListener("click", function () {
                    movePlayerTo(row, col);
                    gameGrid.focus();
                });
                gameGrid.appendChild(cell);
            }
        }

        const inputs = {
            w: false,
            a: false,
            s: false,
            d: false
        };

        window.onkeyup = function(e) {
            switch (e.key) {
                case "w":
                    inputs.w = false;
                    break;
                case "a":
                    inputs.a = false;
                    break;
                case "s":
                    inputs.s = false;
                    break;
                case "d":
                    inputs.d = false;
                    break;
            }
        };

        window.onkeydown = function(e) {
            switch (e.key) {
                case "w":
                    inputs.w = true;
                    break;
                case "a":
                    inputs.a = true;
                    break;
                case "s":
                    inputs.s = true;
                    break;
                case "d":
                    inputs.d = true;
                    break;
            }
        };

        const update = () => {
            if (inputs.w) {
                movePlayerTo(currentPlayer.position.y - 1, currentPlayer.position.x);
            }
            if (inputs.a) {
                movePlayerTo(currentPlayer.position.y, currentPlayer.position.x - 1);
            }
            if (inputs.s) {
                movePlayerTo(currentPlayer.position.y + 1, currentPlayer.position.x);
            }
            if (inputs.d) {
                movePlayerTo(currentPlayer.position.y, currentPlayer.position.x + 1);
            }
        };

        setInterval(() => {
            update();
        }, 1000 / 60);

        gameGrid.setAttribute("tabindex", "0");
        gameGrid.focus();
    }

    function updatePlayerPosition(movedPlayer) {
        // 更新单个玩家的位置
        if (!movedPlayer || !movedPlayer.id) {
            console.warn('Invalid player data for position update:', movedPlayer);
            return;
        }

        // 位置验证和修复
        if (!movedPlayer.position) {
            console.warn(`Player ${movedPlayer.username || movedPlayer.id} has no position, setting default`);
            movedPlayer.position = { x: 0, y: 0 };
        } else {
            // 确保位置在有效范围内
            const x = Math.max(0, Math.min(49, movedPlayer.position.x));
            const y = Math.max(0, Math.min(49, movedPlayer.position.y));
            
            if (x !== movedPlayer.position.x || y !== movedPlayer.position.y) {
                console.warn(`修复玩家 ${movedPlayer.username} 的异常位置: (${movedPlayer.position.x}, ${movedPlayer.position.y}) -> (${x}, ${y})`);
                movedPlayer.position = { x, y };
            }
        }
        
        // 如果是当前玩家，同步更新本地位置
        if (currentPlayer && String(movedPlayer.id) === String(currentPlayer.id)) {
            currentPlayer.position = { ...movedPlayer.position };
            console.log(`同步当前玩家位置: (${currentPlayer.position.x}, ${currentPlayer.position.y})`);
        }

        // 清理该玩家在旧位置的元素
        const playerId = String(movedPlayer.id);
        const oldPlayerElement = document.querySelector(`.player[data-id="${playerId}"]`);
        if (oldPlayerElement) {
            oldPlayerElement.remove();
        }

        // 更新网格中的玩家位置
        updatePlayerPositionInGrid(movedPlayer);
        
        // 更新玩家列表中的位置信息
        updatePlayerListPosition(movedPlayer);
        
        console.log(`更新玩家 ${movedPlayer.username} 位置到 (${movedPlayer.position.x}, ${movedPlayer.position.y})`);
    }

    function updatePlayerListPosition(movedPlayer) {
        const playerList = document.getElementById("playerList");
        const listItems = playerList.querySelectorAll("li");
        
        for (let item of listItems) {
            const text = item.textContent;
            if (text.includes(movedPlayer.username)) {
                // 更新位置信息
                const colorIndicator = item.querySelector("span");
                item.innerHTML = '';
                item.appendChild(colorIndicator);
                item.appendChild(document.createTextNode(`${movedPlayer.username} (状态: ${movedPlayer.status}, 位置: (${movedPlayer.position.x}, ${movedPlayer.position.y}))`));
                
                if (currentPlayer && String(movedPlayer.id) === String(currentPlayer.id)) {
                    item.style.fontWeight = "bold";
                    item.style.color = "#007bff";
                }
                break;
            }
        }
    }

    function updatePlayerList(players) {
        var playerList = document.getElementById("playerList");
        playerList.innerHTML = '';

        // 清理所有玩家元素
        document.querySelectorAll('.player').forEach(function(playerElement) {
            playerElement.remove();
        });

        // 清理不存在的玩家
        var currentPlayerIds = players.map(p => String(p.id));
        Object.keys(playerElements).forEach(function(playerId) {
            if (!currentPlayerIds.includes(playerId)) {
                delete playerElements[playerId];
            }
        });
        
        players.forEach(function (player) {
            if (!player.position) {
                console.warn(`Player ${player.username || player.id} has no position, setting default`);
                player.position = { x: 0, y: 0 };
            }

            var listItem = document.createElement("li");
            var playerColor = getPlayerColor(player.id);
            var colorIndicator = document.createElement("span");
            colorIndicator.style.display = "inline-block";
            colorIndicator.style.width = "12px";
            colorIndicator.style.height = "12px";
            colorIndicator.style.borderRadius = "50%";
            colorIndicator.style.backgroundColor = playerColor;
            colorIndicator.style.marginRight = "8px";
            colorIndicator.style.verticalAlign = "middle";

            listItem.appendChild(colorIndicator);
            listItem.appendChild(document.createTextNode(`${player.username} (状态: ${player.status}, 位置: (${player.position.x}, ${player.position.y}))`));

            if (currentPlayer && String(player.id) === String(currentPlayer.id)) {
                listItem.style.fontWeight = "bold";
                listItem.style.color = "#007bff";
            }

            playerList.appendChild(listItem);
            updatePlayerPositionInGrid(player);
        });

        console.log(`更新玩家列表，当前房间玩家数量: ${players.length}`);
    }



    let clock = 0

    function movePlayerTo(row, col) {
        if (!currentPlayer) return;
        
        // 边界检查和位置验证
        const oldX = currentPlayer.position.x;
        const oldY = currentPlayer.position.y;
        
        // 确保新位置在有效范围内
        row = Math.max(0, Math.min(49, row));
        col = Math.max(0, Math.min(49, col));
        
        // 检查位置是否真的改变了
        if (row === oldY && col === oldX) {
            console.log('位置未改变，跳过更新');
            return;
        }
        
        // 清理旧位置的玩家元素
        const oldCell = document.querySelector(`.cell[data-x="${oldX}"][data-y="${oldY}"]`);
        if (oldCell) {
            const oldPlayerElement = oldCell.querySelector(`.player[data-id="${currentPlayer.id}"]`);
            if (oldPlayerElement) {
                oldPlayerElement.remove();
            }
        }
        
        // 更新位置
        currentPlayer.position = { x: col, y: row };
        updatePlayerPositionInGrid(currentPlayer);
        
        // 发送位置更新到服务器
        if (socket && socket.readyState === WebSocket.OPEN) {
            clock++
            if(clock%1===0){
                const message = new ProtobufMessage();
                message.setBase(MessageType.UPDATE_PLAYER, currentPlayer.id, currentRoom);
                message.setUpdatePlayer(currentPlayer);
                
                socket.send(message.toJSON());
            }
        }
        
        console.log(`玩家移动到新位置: (${col}, ${row})`);
    }

    function updatePlayerPositionInGrid(player) {
        if (!player || !player.id) {
            console.warn('Invalid player data:', player);
            return;
        }

        if (!player.position) {
            console.warn(`Player ${player.username || player.id} has no position, setting default`);
            player.position = { x: 0, y: 0 };
        }

        const playerId = String(player.id);
        let playerElement = playerElements[playerId];

        if (!playerElement) {
            playerElement = document.createElement("div");
            playerElement.classList.add("player");
            playerElement.setAttribute("data-id", playerId);
            playerElement.setAttribute("data-username", player.username);

            const playerColor = getPlayerColor(playerId);
            playerElement.style.backgroundColor = playerColor;
            playerElement.title = player.username;
            playerElement.textContent = player.username.charAt(0);

            if (currentPlayer && String(playerId) === String(currentPlayer.id)) {
                playerElement.style.border = "3px solid #000";
                playerElement.style.boxShadow = "0 0 10px rgba(0,0,0,0.5)";
            }

            playerElements[playerId] = playerElement;
        }

        const cell = document.querySelector(`.cell[data-x="${player.position.x}"][data-y="${player.position.y}"]`);
        if (cell) {
            // 检查是否已经存在该玩家的元素
            const existingPlayer = cell.querySelector(`.player[data-id="${playerId}"]`);
            if (existingPlayer) {
                // 如果该玩家已存在，不需要重复添加
                return;
            }
            
            // 如果位置上有其他玩家，创建重叠显示效果
            const existingPlayers = cell.querySelectorAll('.player');
            if (existingPlayers.length > 0) {
                // 调整当前玩家的z-index，让它显示在其他玩家之上
                playerElement.style.zIndex = existingPlayers.length + 1;
                // 稍微偏移位置，避免完全重叠
                const offset = existingPlayers.length * 2;
                playerElement.style.transform = `translate(${offset}px, ${offset}px)`;
            }
            
            cell.appendChild(playerElement);
        } else {
            console.warn(`Cell not found for position (${player.position.x}, ${player.position.y})`);
        }
    }

    function getPlayerColor(playerId) {
        const colors = [
            '#007bff', '#28a745', '#dc3545', '#ffc107', '#6f42c1',
            '#fd7e14', '#20c997', '#e83e8c', '#6c757d', '#17a2b8',
            '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57',
            '#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3', '#ff9f43'
        ];

        const playerIdStr = String(playerId || '');
        const colorIndex = Math.abs(hashCode(playerIdStr)) % colors.length;
        return colors[colorIndex];
    }

    function hashCode(str) {
        let hash = 0;
        if (str.length === 0) return hash;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }
        return hash;
    }

    function sendEmoji(emoji) {
        if (!currentPlayer || !currentRoom || !socket || socket.readyState !== WebSocket.OPEN) {
            return;
        }

        const message = new ProtobufMessage();
        message.setBase(MessageType.EMOJI_SENT, currentPlayer.id, currentRoom);
        message.setEmojiSent(emoji, currentPlayer.username, currentPlayer.id);
        
        console.log('发送protobuf表情包消息:', message.toJSON());
        socket.send(message.toJSON());
        
        // 立即在自己的方形内显示表情包
        const playerIdStr = String(currentPlayer.id);
        const playerElement = playerElements[playerIdStr];
        
        if (playerElement) {
            playerElement.textContent = emoji;
            
            // 3秒后恢复显示用户名
            setTimeout(() => {
                if (playerElement && playerElement.getAttribute('data-username')) {
                    playerElement.textContent = playerElement.getAttribute('data-username').charAt(0);
                }
            }, 3000);
        }
    }

    function showEmojiAnimation(emoji, username, playerId) {
        const playerIdStr = String(playerId);
        const playerElement = playerElements[playerIdStr];
        
        if (playerElement) {
            // 在玩家方形内显示表情包
            playerElement.textContent = emoji;
            
            // 3秒后恢复显示用户名
            setTimeout(() => {
                if (playerElement && playerElement.getAttribute('data-username')) {
                    playerElement.textContent = playerElement.getAttribute('data-username').charAt(0);
                }
            }, 3000);
        }
    }
    
    function highlightCurrentPlayer() {
        if (!currentPlayer) return;
        
        const playerId = String(currentPlayer.id);
        const playerElement = playerElements[playerId];
        
        if (playerElement) {
            // 移除之前的动画类
            playerElement.classList.remove('player-highlight');
            
            // 强制重绘
            void playerElement.offsetWidth;
            
            // 添加闪烁动画
            playerElement.classList.add('player-highlight');
            
            // 动画结束后移除类
            setTimeout(() => {
                playerElement.classList.remove('player-highlight');
            }, 3000);
        }
    }

    document.addEventListener('keydown', function(event) {
        if (!currentPlayer || !currentRoom) {
            return;
        }

        if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
            return;
        }

        // 确保当前玩家位置有效
        if (!currentPlayer.position) {
            console.warn('当前玩家位置无效，重置到中心位置');
            currentPlayer.position = { x: 25, y: 25 };
        }

        const currentX = currentPlayer.position.x;
        const currentY = currentPlayer.position.y;
        let newX = currentX;
        let newY = currentY;

        switch(event.key) {
            case 'ArrowUp':
            case 'w':
            case 'W':
                newY = Math.max(0, currentY - 1);
                break;
            case 'ArrowDown':
            case 's':
            case 'S':
                newY = Math.min(49, currentY + 1);
                break;
            case 'ArrowLeft':
            case 'a':
            case 'A':
                newX = Math.max(0, currentX - 1);
                break;
            case 'ArrowRight':
            case 'd':
            case 'D':
                newX = Math.min(49, currentX + 1);
                break;
            case 'r':
            case 'R':
                // 重置位置到中心
                console.log('重置玩家位置到中心');
                movePlayerTo(25, 25);
                event.preventDefault();
                return;
            default:
                return;
        }

        if (newX !== currentX || newY !== currentY) {
            movePlayerTo(newY, newX);
            event.preventDefault();
        }
    });



    window.addEventListener('beforeunload', function() {
        console.log("页面已关闭或刷新");
        if (currentPlayer && socket && socket.readyState === WebSocket.OPEN) {
            sendLeaveGame();
        }
    });

    window.addEventListener('online', function() {
        console.log('网络已连接');
    });

    window.addEventListener('offline', function() {
        console.log('网络已断开');
        if (currentPlayer) {
            alert('网络连接已断开，请检查网络后刷新页面');
        }
    });


</script>

</body>
</html>
